package com.ruoyi.project.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.custom.domain.CustomInfo;
import com.ruoyi.project.custom.service.ICustomInfoService;
import com.ruoyi.project.shop.domain.ShopInfo;
import com.ruoyi.project.shop.domain.ShopOperator;
import com.ruoyi.project.shop.domain.vo.ShopOperatorVo;
import com.ruoyi.project.shop.service.IShopInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shop")
public class ShopInfoController extends BaseController {
    @Autowired
    private IShopInfoService shopService;
    @Autowired
    private ICustomInfoService customService;

    @GetMapping("/list")
    public TableDataInfo selectShopList(ShopInfo shopInfo)
    {
        startPage();
        List<ShopInfo> list = shopService.selectShopList(shopInfo);
        return getDataTable(list);
    }

    @GetMapping("/selectShopById/{id}")
    public AjaxResult selectShopById(@PathVariable String id)
    {
        return AjaxResult.success(shopService.selectShopById(id));
    }

    @Log(title = "新增店铺", businessType = BusinessType.INSERT)
    @PostMapping("/insertShop")
    public AjaxResult insertShop(@RequestBody ShopInfo shopInfo)
    {
        return shopService.insertShop(shopInfo);
    }

    @Log(title = "修改店铺", businessType = BusinessType.UPDATE)
    @PutMapping("/updateShop")
    public AjaxResult updateShop(@RequestBody ShopInfo shopInfo)
    {
        return shopService.updateShop(shopInfo);
    }

    @Log(title = "更新店铺状态", businessType = BusinessType.UPDATE)
    @PutMapping("/updateShopStatus")
    public AjaxResult updateShopStatus(@RequestBody ShopInfo shopInfo)
    {
        return shopService.updateShop(shopInfo);
    }

    @Log(title = "删除店铺", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteShop/{id}")
    public AjaxResult deleteShop(@PathVariable String id)
    {
        return toAjax(shopService.deleteShop(id));
    }

    @Log(title = "分配运营人员", businessType = BusinessType.UPDATE)
    @PutMapping("/assignOperators")
    public AjaxResult assignOperators(@RequestBody ShopOperatorVo shopOperatorVo)
    {
        List<ShopOperator> operatorList = new ArrayList<>();
        if(shopOperatorVo.getShopIds() != null && shopOperatorVo.getShopIds().length > 0){
            for(String shopId : shopOperatorVo.getShopIds()){
                for(String operatorId : shopOperatorVo.getOperators()){
                    ShopOperator operator = new ShopOperator();
                    operator.setShopId(shopId);
                    operator.setUserId(operatorId);
                    operatorList.add(operator);
                }
            }
        }

        return shopService.assignOperators(operatorList);
    }

    @Log(title = "转交店铺", businessType = BusinessType.UPDATE)
    @PutMapping("/transferOperators")
    public AjaxResult transferOperators(@RequestBody ShopOperatorVo shopOperatorVo)
    {
        List<ShopOperator> operatorList = new ArrayList<>();
        if(shopOperatorVo.getShopIds() != null && shopOperatorVo.getShopIds().length > 0){
            for(String shopId : shopOperatorVo.getShopIds()){
                for(String operatorId : shopOperatorVo.getOperators()){
                    ShopOperator operator = new ShopOperator();
                    operator.setShopId(shopId);
                    operator.setUserId(operatorId);
                    operatorList.add(operator);
                }
            }
        }

        return shopService.transferOperators(operatorList);
    }

    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file)
    {
        if(file.isEmpty()){
            return AjaxResult.error("文件为空！");
        }
        String oldFileName = file.getOriginalFilename();
        if(oldFileName ==null) {
            return AjaxResult.error("请上传正确格式的excel！");
        }
        if (!(oldFileName.toLowerCase().endsWith("xls") || oldFileName.toLowerCase().endsWith("xlsx"))){
            return AjaxResult.error( "请上传正确格式的excel");
        }

        try{
            List<ShopInfo> list = null;
            ExcelUtil<ShopInfo> util = new ExcelUtil<>(ShopInfo.class);
            list = util.importExcel(null, file.getInputStream(), 1, 0);
            if (list == null || list.size() == 0){
                return AjaxResult.error( "excel 数据为空");
            }
            if (list.size() > 500){
                return AjaxResult.error("导入失败，超出最大导入限制500条，请删减后重新导入");
            }

            List<String> errList = checkTemplate(list);
            if(errList.size() == 0){
                shopService.importShop(list);
            }
            else{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("errMsg", errList);
                return AjaxResult.success("导入错误", jsonObject);
            }

        }catch(Exception e){
            return AjaxResult.error("请检查导入模板是否正确！");
        }

        return AjaxResult.success();
    }

    @Log(title = "导出店铺信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult exportExcel(ShopInfo shopInfo)
    {
        List<ShopInfo> list = shopService.selectShopList(shopInfo);
        ExcelUtil<ShopInfo> util = new ExcelUtil<ShopInfo>(ShopInfo.class);
        return util.exportExcel(list, "店铺信息");
    }

    private List<String> checkTemplate(List<ShopInfo> shopList)
    {
        List<String> errList = new ArrayList<>();
        for (int i = 0; i < shopList.size(); i++)
        {
            StringBuilder errMsg = new StringBuilder();
            ShopInfo shop = shopList.get(i);

            // 检查客户名称
            if(StringUtils.isEmpty(shop.getCusName().trim())){
                errMsg.append("企业名称不能为空；");
            }else {
                CustomInfo customInfo = customService.selectCustomByName(shop.getCusName());
                if (customInfo == null) {
                    errMsg.append("企业名称在系统中不存在；");
                }
            }

            // 检查店铺名称
            if(StringUtils.isEmpty(shop.getName().trim())){
                errMsg.append("店铺名称不能为空；");
            }else{
                if(shop.getName().length() > 100){
                    errMsg.append("店铺名称长度不能超过100个字符；");
                }
            }

            // 检查店铺网址
            if(StringUtils.isNotEmpty(shop.getShopUrl().trim())){
                if(shop.getShopUrl().length() > 200){
                    errMsg.append("店铺名称长度不能超过200个字符；");
                }
            }

            // 检查服务类型
            if(StringUtils.isEmpty(shop.getServiceType())){
                errMsg.append("请选择正确的服务类型；");
            }

            // 检查店铺账号
            if(StringUtils.isEmpty(shop.getAccount().trim())){
                errMsg.append("店铺账号不能为空；");
            }else{
                if(shop.getAccount().length() > 100){
                    errMsg.append("店铺账号长度不能超过100个字符；");
                }else{
                    if(shopService.checkShopByAccount(shop) > 0){
                        errMsg.append("已存在相同的店铺账号了；");
                    }
                }
            }

            // 检查店铺密码
            if(StringUtils.isEmpty(shop.getPassword())){
                errMsg.append("店铺密码不能为空；");
            }else{
                if(shop.getPassword().length() > 100){
                    errMsg.append("店铺密码长度不能超过100个字符；");
                }
            }

            // 检查店铺密码
            if(StringUtils.isEmpty(shop.getWechatGroup())){
                errMsg.append("微信群不能为空；");
            }else{
                if(shop.getWechatGroup().length() > 100){
                    errMsg.append("微信群长度不能超过100个字符；");
                }
            }

            if(errMsg.length() > 0){
                errList.add("第" + (i + 1) + "行：" + errMsg.toString());
            }
        }

        return errList;
    }
}
